package com.chixing.controller;

import com.chixing.pojo.*;
import com.chixing.service.*;
import com.chixing.util.DateUtil;
import com.chixing.util.ServerResult;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.chixing.util.DateUtil.DATE_PATTERN_YMDHM;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private BranchService branchService;

    @Autowired
    private CarService carService;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private CouponService couponService;

    @Autowired
    private AmqpTemplate rabbitTemplate;


    @Autowired
    private PianhaoService pianhaoService;
    //预定
    @GetMapping("/order")
    @ResponseBody
    public ModelAndView getOrderInfo(@RequestParam("cusId") Integer cusId, @RequestParam("carId") Integer carId,
                                     @RequestParam("getCarShop") String getCarShop, @RequestParam("returnCarShop") String returnCarShop,
                                     @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate,
                                     @RequestParam("carName") String carName, @RequestParam("price") Float price,
                                     @RequestParam("getCity") String getCity, @RequestParam("returnCity") String returnCity,HttpSession session) {

        System.out.println("cusId:" + cusId);
        System.out.println("carId:" + carId);
        System.out.println("getCarShop:" + getCarShop);
        System.out.println("returnCarShop:" + returnCarShop);
        System.out.println("startDate:" + startDate);
        System.out.println("endDate:" + endDate);
        System.out.println("carName:" + carName);
        System.out.println("price:" + price);

        startDate.replace(":", "-");
//        System.out.println(startDate);
        Date getCarDate = DateUtil.string2Date(startDate, DATE_PATTERN_YMDHM);
//        System.out.println(getCarDate);

        endDate.replace(":", "-");

        Date returnDate = DateUtil.string2Date(endDate, DATE_PATTERN_YMDHM);
        Myorder myorder = new Myorder();

        //租车天数
        int day = (int) (returnDate.getTime() - getCarDate.getTime()) / (24 * 60 * 60 * 1000);

        int startShopId = branchService.getByNameCity(getCarShop, getCity).getShopId();
        int endShopId = branchService.getByNameCity(returnCarShop, returnCity).getShopId();

        ModelAndView mav = new ModelAndView();

        if (branchService.getByNameCity(getCarShop, getCity) == null) {
            mav.addObject("result", "您所选择的店铺不存在");
            mav.setViewName("car_rental/car-search");
            System.out.println(mav);
            return mav;
        }


        myorder.setMemberId(cusId);//用户id
        myorder.setGetShopId(startShopId);//取车萌呆呢id
        myorder.setReturnShopId(endShopId);//还车门店id
        myorder.setGetCarDate(getCarDate);//取车时间
        myorder.setBackCarDate(returnDate);//还车时间
        myorder.setCarId(carId);//车辆id
        myorder.setCarDay(day);//租车天数
        myorder.setMyorderRawprice(price);//原始价格
        myorder.setMyorderTotalPrice(day * price); //总价格

        String startAdd = branchService.getAddById(startShopId);// 取车地址
        String endAdd = branchService.getAddById(endShopId);// 还车地址

        Member member = (Member) session.getAttribute("customer");
        ServerResult serverResult = couponService.getUserCoupon(member.getMemberId());
        if (serverResult.getCode() == 200)
            mav.addObject("mycoupon", serverResult.getData());

        mav.addObject("orderInfo", myorder);
        mav.addObject("carName", carName);
        mav.addObject("startDate", startDate);
        mav.addObject("endDate", endDate);
        mav.addObject("getCarShop", getCarShop);
        mav.addObject("returnCarShop", returnCarShop);
        mav.addObject("startAdd", startAdd);
        mav.addObject("endAdd", endAdd);
        mav.setViewName("order/create_order");

        System.out.println("订单详情");
        System.out.println(mav);

        return mav;
    }


    @PostMapping("/myorder")
    public ModelAndView save(Myorder myorder) {

        System.out.println("前端传回得订单" + myorder);

        String orderNum = UUID.randomUUID().toString().replace("-", "");
        System.out.println("UUID生成的订单编号" + orderNum);
        myorder.setMyorderNumber(orderNum);
        myorder.setMyorderStatus(0);
        myorder.setMyorderDate(new Date());

        System.out.println("下达的订单信息：" + myorder);
        pianhaoService.pianhao2Update(myorder.getMemberId(), myorder.getCarId(), 4.0f);
        ServerResult serverResult = orderService.save(myorder);
        Integer myorderId = myorder.getMyorderId ();
        System.out.println ("订单编号======="+myorderId);

        rabbitTemplate.convertAndSend ("orderExchange","routingKey",myorderId + "");
        System.out.println("OrderController.submit... sendMessage to orderExchange");

        System.out.println("添加到数据库后，订单的信息：" + serverResult.getCode());
        ModelAndView mav = new ModelAndView();
        if (serverResult.getCode() == 200) {
//            couponService.updateById(myorder.getCouponNo());
            mav.setViewName("order/gopay");
            mav.addObject("myorder", serverResult.getData());
        }

        return mav;

    }

    @GetMapping("/ordermanage")
    public ModelAndView getOrderManage(HttpSession session) {
        System.out.println("查看订单详情");
        Member member = (Member) session.getAttribute("customer");
        ModelAndView mav = new ModelAndView();
        System.out.println("用户id" + member.getMemberId());
        List<Myorder> myorderList = orderService.getOrderdetail(member.getMemberId());
        mav.addObject("memberdetail", member);
        mav.addObject("myorderList", myorderList);
        for (Myorder myorder : myorderList) {
            System.out.println("订单信息" + myorder);
            pianhaoService.pianhao2Update(myorder.getMemberId(), myorder.getCarId(),5.0f);
            Car car = carService.getById(myorder.getCarId());
            mav.addObject("cardetail", car);
        }
        mav.setViewName("order/order_manage");
        return mav;
    }

    @GetMapping("/orderdetail")
    public ModelAndView getOrderdetail(@RequestParam("orderId") Integer orderId, HttpSession session) {
        System.out.println("查看订单详情");
        Member member = (Member) session.getAttribute("customer");

        ModelAndView mav = new ModelAndView();

        Myorder myorder = orderService.getById(orderId);
        mav.addObject("memberdetail", member);
        System.out.println("订单信息" + myorder);
        Car car = carService.getById(myorder.getCarId());
        ServerResult getShop = branchService.getByShopId(myorder.getGetShopId());
        ServerResult returnShop = branchService.getByShopId(myorder.getReturnShopId());
        List<Review> reviewList = reviewService.getById(myorder.getMyorderNumber());
        mav.addObject("returnShopDetail", returnShop);
        mav.addObject("getShopDetail", getShop);
        mav.addObject("cardetail", car);
        mav.addObject("orderdetail", myorder);
        mav.addObject("review", reviewList);

        OwnCoupon ownCoupon = couponService.getById(myorder.getCouponNo());
        mav.addObject("ownCoupon",ownCoupon);

        mav.setViewName("order/order_detail");
        return mav;
    }

    @GetMapping("myorder/{memberId}/{couponNo}")
    public String getByCouponOrder(@PathVariable("memberId") Integer memberId,
                                   @PathVariable("couponNo") Integer couponNo) {

        Myorder myorder = orderService.getByCouponOrder(memberId, couponNo);

        return "redirect:/orderdetail?orderId=" + myorder.getMyorderId();


    }

}

